#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/select.h>
#include <sys/epoll.h>
#include <pthread.h>
#include "pool.h"

pthread_mutex_t mutex;

int epoll_fd;

int create_tcp_server_socket(char *ip, int port)
{
    signal(SIGPIPE, SIG_IGN);

    int sockfd;
    int sockaddr_len;

    struct in_addr server_ip;
    struct sockaddr_in server_addr;
    // 1、socket函数创建套接字 -->  文件描述符
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        perror("socket create failed!\n");
        exit(1);
    }
    printf("socket create Success! %d\n", sockfd);

    int reuse = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));

    //??为什么要绑定IP和端口号？接受客户端的连接，就需要确定服务器的IP和端口号
    // 2、bind：给套接字绑定IP地址和端口号
    // 初始化struct sockadd_in变量；

    inet_pton(AF_INET, ip, (void *)&server_ip);
    server_addr.sin_family = AF_INET;   // IPV4
    server_addr.sin_addr = server_ip;   // IP
    server_addr.sin_port = htons(port); // h:host to n:net

    if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)) < 0)
    {
        perror("bind ip & port failed!");
        exit(1);
    }
    printf("bind Success ip = %s port = %d\n", ip, port);

    // 3、listen：监听：允许其他人进行连接请求
    if (listen(sockfd, 20) < 0)
    {
        perror("listen failed!\n");
        exit(1);
    }
    printf("listen Success!\n");

    return sockfd;
}

void setnonblock(int sockfd)
{
    int flags = fcntl(sockfd, F_GETFL);
    flags = flags | O_NONBLOCK;
    fcntl(sockfd, F_SETFL, flags);
}

void read_client_msg (void *arg)
{
    long fd = (long)arg;
    char buffer[1024];
    ssize_t bytes_read;

    //
    while ((bytes_read = read(fd, buffer, 1024)) > 0)
    {
        printf("Received [%zd] bytes:%s\n", bytes_read, buffer);
        write(fd, buffer, bytes_read); // 回显数据
    }

    if (bytes_read == 0 || (bytes_read == -1 && errno != EAGAIN))
    {
        pthread_mutex_lock(&mutex);
        epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, NULL);
        pthread_mutex_unlock(&mutex);
        close(fd);
        printf("Connection closed\n");
    }
}

int main(int argc, char **argv)
{
    if (argc != 3)
    {
        printf("Please input server bind ip and port!\n");
        exit(1);
    }

    int fd;
    int sockfd;
    int r_len;
    int rnums;
    int confd;
    int tempfd;
    int sockaddr_len;
    char message[1024] = {0};
    char client_ip[INET_ADDRSTRLEN];
    struct sockaddr_in client_addr;
    struct epoll_event read_event[1024];

    pthread_mutex_init(&mutex, NULL);

    // 创建epoll监听的红黑树的文件描述符//epoll_create1();
    epoll_fd = epoll_create1(0);
    if (epoll_fd < 0)
    {
        perror("epoll create error!");
        exit(1);
    }

    int client_fds[__FD_SETSIZE];
    for (int i = 0; i < __FD_SETSIZE; i++)
    {
        client_fds[i] = -1;
    }

    sockfd = create_tcp_server_socket(argv[1], atoi(argv[2]));
    // select:sockfd:当有客户端连接服务器时，sockfd呈现读状态
    struct epoll_event *event = (struct epoll_event *)malloc(sizeof(struct epoll_event));
    event->data.fd = sockfd;
    event->events = EPOLLIN | EPOLLET;
    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sockfd, event);

    struct thread_pool *pool = thread_pool_create(30, 100, 10000);

    while (1)
    {
        rnums = epoll_wait(epoll_fd, read_event, 1024, -1);
        if (rnums < 0)
        {
            perror("select error!");
            break;
        }
        printf("enable read fd nums = [%d]\n", rnums);

        for (int i = 0; i < rnums; i++)
        {
            if ((read_event[i].data.fd == sockfd) && (read_event[i].events == EPOLLIN))
            {
                sockaddr_len = sizeof(struct sockaddr);
                confd = accept(sockfd, (struct sockaddr *)&client_addr, (socklen_t *)&sockaddr_len);
                if (confd < 0)
                {
                    perror("accept failed!");
                    exit(1);
                }
                else
                {
                    inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, sizeof(client_ip));
                    printf("client ip = %s port = %d\n", client_ip, client_addr.sin_port);
                    event = (struct epoll_event *)malloc(sizeof(struct epoll_event));
                    setnonblock(confd);
                    event->data.fd = confd;
                    event->events = EPOLLIN | EPOLLET;
                    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, confd, event);
                }
            }
            else
            {
                if (read_event[i].events == EPOLLIN)
                {
                    int fd = read_event[i].data.fd;
                    // ？？读任务放到任务队列，可能不会及时读客户端数据（频繁上锁和解锁），此时主线程wait，如果LT水平，就会再次响应；如果ET边沿方式，只响应一次
                    thread_add_job(pool, read_client_msg, (void *)(long)fd);
                }
            }
        }
    }

    // 6、close/shutdown： 关闭连接

    return 0;
}